package com.nulldev.util.net.protocols.openSDTP2.transferTest;

import com.nulldev.util.net.IPUtil;
import com.nulldev.util.net.packets.NetInfoAdapter;
import com.nulldev.util.net.packets.NetPacket;
import com.nulldev.util.net.packets.PacketManager;
import com.nulldev.util.net.tcp.TCPCore;
import com.nulldev.util.net.tcp.client.TCPClient;
import com.nulldev.util.net.tcp.server.TCPServer;
import com.nulldev.util.java.JVMUtil;
import com.nulldev.util.other.ByteUtils;
import com.nulldev.util.math.MathUtil;
import com.nulldev.util.io.FileUtil;

public class SpeedTestDemo {

	public static void main(String[] args) {
		final int port = IPUtil.nextFreePort();
		final TCPServer tcps = new TCPServer("SpeedTest Demo Server", "speedTest.server", port, true) {
			
			@Override
			public void receive(TCPCore connection, String event, String payload, byte[] bytes, long length, long readTime) {
				final NetPacket packet = PacketManager.parsePacket(this, connection, event, bytes, readTime);
				if (!packet.isGeneric()) {
					packet.server(packet.getData(), event, NetInfoAdapter.create(connection)
							.applyReadTimeData(readTime));
				}
			}
		};
		tcps.start();
		final String ip = tcps.getIP();
		final TCPClient tcpc = new TCPClient("SpeedTest Demo Client", "speedTest.client") {
			
			@Override
			public void receive(String event, String payload, byte[] bytes, long count, long readTime) {
				final NetPacket packet = PacketManager.parsePacket(this, null, event, bytes, readTime);
				if (!packet.isGeneric()) {
					packet.client(packet.getData(), event, NetInfoAdapter.create(this.getConnection())
							.applyReadTimeData(readTime));
				}
			}
		};
		tcpc.PREFER_THREAD_API = true;
		tcpc.start();
		tcpc.updateHost(ip, port);
		if (!tcpc.waitForConnection(1000)) {
			throw new UnsupportedOperationException("Unable to connect.");
		}
		if (tcpc.createKeyPair()) {
			JVMUtil.async_println("createKeyPair(): OK.");
		}else{
			JVMUtil.async_error("createKeyPair(): FAILED");
		}
		final int payloadSize = MathUtil.secureRandInt(64 * 1024, 32 * 1024 * 1024);
		JVMUtil.async_println("Sending a payload of " + FileUtil.convertToStringRepresentation(payloadSize) + ".");
		tcpc.sendBlocking(new DataTransferPacket(payloadSize));
		try {
			Thread.sleep(5L);
		} catch (InterruptedException e) {
		}
		JVMUtil.async_println("Sent speed tests.");	
	}

}
